<template>
 <el-breadcrumb class="app-breadcrumb" separator="/">
    <el-breadcrumb-item v-if="!isDashboard(this.$route)">
      <el-button @click.prevent="goToDashboard()"><Icon name="el-icon-Back" color="#000" /><span>Dashboard</span></el-button>
    </el-breadcrumb-item>
    <el-breadcrumb-item v-for="(item,index) in itemList" :key="item.path">
      <span v-if="item.redirect==='noRedirect'||index==itemList.length-1"
        class="no-redirect">{{ item.meta.title }}</span>
      <a v-else @click.prevent="handleLink(item)">{{ item.meta.title }}</a>
    </el-breadcrumb-item>
  </el-breadcrumb>
</template>

<script>
import { defineComponent } from "vue";
import {pathToRegexp} from "path-to-regexp";
export default defineComponent({
  name:"breadcrumb",
  data() {
    return {
      itemList: [],
    };
  },
  watch: {
    $route() {
      this.getBreadcrumb();
    },
  },
  methods: {
    goToDashboard(){
      this.$router.push({
        name:"Dashboard"
      })
    },
    getBreadcrumb() {
      let currentRoute = this.$route;
      let matched = currentRoute.matched.filter(
        (item) => item.meta && item.meta.title
      );
        this.itemList = matched
    },
    isDashboard(route) {
      const name = route && route.name;
      if (!name) {
        return false;
      }
      return name.trim().toLocaleLowerCase() === "Dashboard".toLocaleLowerCase();
    },
    pathCompile(path) {
      // To solve this problem https://github.com/PanJiaChen/vue-element-admin/issues/561
      const { params } = this.$route;
      return pathToRegexp(path,params);
    },
    handleLink(item) {
      const { redirect, path } = item;
      if (redirect) {
        this.$router.push(redirect);
        return;
      }
      console.log(this.pathCompile(path))

      this.$router.push(this.pathCompile(path));
    },
    findRoute(name) {
      for (var i = 0; i < this.routes.length - 1; i++) {
        if (this.routes[i].children) {
          return this.routes[i].children.find((e) => e.name == name);
        }
      }
      return false;
    },
  },
});
</script>
<style lang="scss" scoped>
.app-breadcrumb.el-breadcrumb {
  display: inline-block;
  font-size: 14px;
  line-height: 50px;
  margin-left: 8px;

  .no-redirect {
    // color: #97a8be;
    cursor: text;
  }
  .el-button{
    border: none;
    padding-left: 0;
    padding-right: 0;
  }
}
svg {
  width: 40px;
  height: 40px;
  color: red;
}
</style>
